package com.lvy.hczn.front.business.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.lvy.hczn.front.business.common.CacheConstants;
import com.lvy.hczn.front.business.common.Constants;
import com.lvy.hczn.front.common.core.domain.entity.SysDictData;
import com.lvy.hczn.front.common.utils.DictUtils;
import com.lvy.hczn.front.system.domain.business.WarehousingEntry;
import com.lvy.hczn.front.business.dto.Param;
import com.lvy.hczn.front.business.service.PurchaseOrderDetailService;
import com.lvy.hczn.front.business.service.WarehousingEntryService;
import com.lvy.hczn.front.business.util.ResultUtil;
import com.lvy.hczn.front.common.core.redis.RedisCache;
import com.lvy.hczn.front.common.exception.UtilException;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/wcs/entry/")
@RestController
@Slf4j
public class WarehousingEntryController {

    @Autowired
    private WarehousingEntryService warehousingEntryService;

    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;

    @Autowired
    private RedisCache redisCache;

    @ApiOperation(value = "入库单", notes = "入库单")
    @PostMapping("selectByCode")
    public ResultUtil selectByCode(@RequestBody Param param) {
        try {
            WarehousingEntry warehousingEntry = warehousingEntryService.selectByEntryCodeAndStatus(param.getEntryCode(), Constants.ENTRY_ING, param.getUpOrDownPolicy().getClientId(), param.getDeliveryOrderCode());
            return ResultUtil.ok(warehousingEntry);
        } catch (Exception e) {
            log.error("selectByCode:{}", e);
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                return ResultUtil.failed("系统异常");
            }
        }
    }

    @ApiOperation(value = "入库单列表", notes = "入库单列表")
    @PostMapping("selectByEntryCodeList")
    public ResultUtil selectByEntryCodeAndStatusList(@RequestBody Param param) {
        try {
            List<WarehousingEntry> list = warehousingEntryService.selectByEntryCodeAndStatusList(param.getEntryCode(), Constants.ENTRY_ING, param.getUpOrDownPolicy().getClientId(), param.getDeliveryOrderCode());
            return ResultUtil.ok(list);
        } catch (Exception e) {
            log.error("selectByEntryCodeList:{}", e);
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                return ResultUtil.failed("系统异常");
            }
        }
    }

    @ApiOperation(value = "入库单", notes = "入库单")
    @PostMapping("selectEntryCodeByClient")
    public ResultUtil selectEntryCodeByClient(@RequestBody Param param) {
        try {
            //todo clientId 校验
            /*String key = CacheConstants.REDIS_KEY_SOCKET_CLIENT + ":" + param.getUpOrDownPolicy().getClientId() + ":deliverOrderCode";
            String result = (String) redisCache.get(key);
            if (StrUtil.isEmpty(result)) {
                return ResultUtil.failed();
            }
            return ResultUtil.ok(result);*/


            JSONArray array = (JSONArray) redisCache.get(CacheConstants.DICT_TYPE_WH_COM);
            //存在在数据字典中，则发送到前端
            boolean exist = false;
            //目前只允许一台电脑采购入库，单其他电脑采购入库时，提示已有采购入库单，让其等待
            boolean scanClient = false;
            String result = "";
            /**获取上一个下架货箱的仓库index**/
            if (array != null && !array.isEmpty()) {
                for (Object o : array) {
                    SysDictData data = (SysDictData) o;
                    String key = CacheConstants.REDIS_KEY_SOCKET_CLIENT + ":" + data.getDictValue() + ":deliverOrderCode";
                    String resultInfo = (String) redisCache.get(key);
                    if (!StrUtil.isEmpty(resultInfo)) {
                        exist = true;
                        result = resultInfo;
                        if (data.getDictValue().equals(param.getUpOrDownPolicy().getClientId())) {
                            scanClient = true;
                        }
                        break;
                    }
                }
            }
            if (exist) {
                if (scanClient) {
                    //登录电脑匹配时
                    return ResultUtil.ok(result);
                } else {
                    //当有采购入库单正在入库时，其他要再其他电脑上想入库的单据，提示等待，入库暂时只能一个一个入
                    return ResultUtil.failedWithCode(-1, result);
                }
            } else {
                //没有采购入库单据时
                return ResultUtil.failed();
            }
        } catch (Exception e) {
            log.error("selectEntryCodeByClient:｛｝", e);
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                return ResultUtil.failed("系统异常");
            }
        }
    }

    @ApiOperation(value = "清除操作人员的入库单绑定", notes = "清除操作人员的入库单绑定")
    @PostMapping("clearEntryCodeByClient")
    public ResultUtil clearEntryCodeByClient(@RequestBody Param param) {
        try {
            //todo clientId 校验
            String key = CacheConstants.REDIS_KEY_SOCKET_CLIENT + ":" + param.getUpOrDownPolicy().getClientId() + ":deliverOrderCode";
            redisCache.del(key);
            return ResultUtil.ok();
        } catch (Exception e) {
            log.error("clearEntryCodeByClient:{}", e);
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                return ResultUtil.failed("系统异常");
            }
        }
    }

    @ApiOperation(value = "提交入库单到平台", notes = "提交入库单到平台")
    @PostMapping("commitToPlatformInfo")
    public ResultUtil commitToPlatformInfo(@RequestBody Param param) {
        try {
            WarehousingEntry warehousingEntry = new WarehousingEntry();
            /*warehousingEntry.setBatchCode("FH2023052400016");
            warehousingEntry.setAssociatedOrderCode("PS202305302024570007");
            warehousingEntry.setDataType(com.lvy.hczn.front.common.constant.Constants.WAREHOUSING_ENTRY_DATA_TYPE_ONE);*/
            warehousingEntry.setDataType("CSRK");
            warehousingEntryService.commitToPlatformInfo(param, warehousingEntry.getDataType(), param.isOutboundAndEntry());
            return ResultUtil.ok();
        } catch (Exception e) {
            log.error("commitToPlatformInfo:{}", e);
            if (e instanceof UtilException) {
                return ResultUtil.failed(e.getMessage());
            } else {
                e.printStackTrace();
                return ResultUtil.failed("系统异常");
            }
        }
    }
}
